const app = getApp();
const apiPrefix = app.globalData.apiPrefix;
import { shareData, setShare, regPhone } from "../../utils/util";

Page({
  data: {
      openType:'',
    id: "",
    videoHeight:0,
    detail: {},
    dialogShow: false,
    dialogOpened: false,
    session_key: "",
    sheetShow: false,
    sheetTitle: "",
    sheetBtnBg: "",

    phoneNumber: "",

    phone: "",
    user: "",

    footerBlank: false,

    autoFocus: false,

    dialogPhoneShow: false,
  },
  bindloadedmetadata(e){
      console.log(e.detail)
      this.setData({
        videoHeight:e.detail.height
      })
  },
  toPath(e){
    
      var item=e.currentTarget.dataset.item;
      console.log(item)
      if(item.atype==1){
        var qr=this.data.detail.qrImgList[0].url;
        wx.navigateTo({
            url: `/pages/card/index?qr=${qr}`,
          });
      }else if(item.atype==2){
        wx.navigateToMiniProgram({
            appId: item.appid,
            path: item.path
        })
      }else if(item.atype==3){
          if(this.data.phone!=''){
            var prompt=this.data.detail.prompt;
            if(prompt!=''&&prompt!=null){
                wx.showToast({
                  title: prompt,
                  icon:'none'
                })
            }
          }
      }
  },
  onLoad(option) {
    const id = option.id || decodeURIComponent(option.scene);
    const dialogOpened = wx.getStorageSync("dialogOpened" + id);
  

    const phone = this.data.phone || wx.getStorageSync("phone" + id);
    this.setData({
      phone,
      phoneNumber: phone,
    });

    this.setData({
      id,
      dialogOpened,
    });
    this.getLogin();
    this.geDetail();

    this.setShare();
  },

  // 分享
  setShare() {
    setShare();
  },

  // 监听分享事件
  onShareAppMessage() {
    const { id, name, shareImg } = this.data.detail;
    return shareData({
      title: name,
      path: `/pages/detail/index?id=${id}`,
      imageUrl: shareImg,
    });
  },

  // 登录
  getLogin() {
    const that = this;
    wx.login({
      provider: "weixin",
      success(res) {
        console.log("res login", res);
        wx.request({
          url: `${apiPrefix}wechat/code`,
          data: {
            code: res.code,
          },
          success(res1) {
            const { data = {} } = res1;
            const { session_key } = data;

            that.setData({
              session_key,
            });

            console.log("this", that);
          },
        });
      },
    });
  },

  // 详情
  geDetail() {
    wx.showLoading();
    const that = this;
    const { id: pageId } = this.data;

    wx.request({
      url: `${apiPrefix}page/${this.data.id}`,
      success(res) {
        const { data = {} } = res;

        const { nameBackground, nameColor, components = [], getPhone } = data;

        const dialogItem = components.find((v) => {
          return v.type === "dialog";
        });
        const { time } = dialogItem || {};
        const dialogShow =
          dialogItem && time === 1 && that.data.dialogOpened ? false : true;

        const footItem = components.find((v) => {
          return v.type === "foot";
        });

        that.setData({
          detail: data,
          dialogShow,
          sheetTitle: footItem?.btnTitle || "登记抢豪礼",
          sheetBtnBg: footItem?.btnColor,
        });

        // 设置 title
        wx.setNavigationBarTitle({
          title: `${data.name}`,
        });
        wx.setNavigationBarColor({
          frontColor: nameColor,
          backgroundColor: nameBackground,
        });

        wx.setStorage({
          key: "dialogOpened" + pageId,
          data: true,
        });

        console.log(that.data.phoneNumber, getPhone);

        if (!that.data.phoneNumber && getPhone) {
          that.setData({
            dialogPhoneShow: true,
          });
        }
      },
      complete() {
        wx.hideLoading();
      },
    });
  },

  // 弹窗关闭
  onDialogClose() {
    this.setData({
      dialogShow: false,
    });
  },

  // 获取手机号
  getPhoneNumber(e) {
    const that = this;
    const { id: pageId } = this.data;
    const { type } = e.currentTarget.dataset;
    const { errMsg, iv, encryptedData } = e.detail;

    console.log("e.detail", e.detail);

    console.log("errMsg", errMsg);

    const sheetShow = type === "sheet" ? true : false;

    if (errMsg === "getPhoneNumber:ok") {
      wx.request({
        url: `${apiPrefix}wechat/decrypt`,
        data: {
          sessionKey: that.data.session_key,
          encryptedData: decodeURIComponent(encryptedData),
          iv: decodeURIComponent(iv),
        },
        success(res) {
          console.log("res decrypt", res);
          const { data = {} } = res;
          const { phoneNumber } = data;

          if (phoneNumber) {
            that.setData({
              phone: phoneNumber,
              phoneNumber,
            });

            wx.setStorage({
              key: "phone" + pageId,
              data: phoneNumber,
            });

            const { name, id } = that.data.detail;
            wx.request({
              url: `${apiPrefix}phone`,
              method: "POST",
              data: {
                name,
                phone: phoneNumber,
                pageId: id,
              },
              complete() {
                var prompt=that.data.detail.prompt;
                if(prompt!=''&&prompt!=null){
                    wx.showToast({
                      title: prompt,
                      icon:'none'
                    })
                }
                that.setData({
                  sheetShow,
                  autoFocus: sheetShow,
                  dialogPhoneShow: false,
                });
              },
            });
          }
        },
        fail() {
          that.setData({
            sheetShow,
            autoFocus: sheetShow,
          });
        },
        complete() {
          that.setData({
            dialogShow: false,
          });
        },
      });
    } else {
      that.setData({
        // dialogShow: false,
        sheetShow,
        autoFocus: sheetShow,
      });
    }
  },

  // 打电话
  onCallPhone(e) {
    const { phone } = e.currentTarget.dataset;
    wx.makePhoneCall({
      phoneNumber: phone,
    });
  },

  // 打开登记
  onSheetOpen(e) {
    const { id: pageId } = this.data;

    const phone = this.data.phone || wx.getStorageSync("phone" + pageId);

    if (!phone) {
      this.getPhoneNumber(e);
    } else {
      this.setData({ sheetShow: true, autoFocus: true });
    }

    // this.setData({
    //   phone,
    // });
  },

  // 关闭登记
  onSheetClose() {
    this.setData({ sheetShow: false, autoFocus: false });
  },

  // 登记
  onSheetSubmit() {
    const that = this;
    const { name, id } = this.data.detail;
    const { user, phone } = this.data;

    if (!user) {
      wx.showToast({
        title: "请输入姓名",
        icon: "error",
      });
      return;
    }

    if (!regPhone.test(phone)) {
      wx.showToast({
        title: "手机号不正确",
        icon: "error",
      });
      return;
    }

    wx.showLoading();
    wx.request({
      url: `${apiPrefix}form`,
      method: "POST",
      data: {
        name,
        phone,
        pageId: id,
        user,
      },
      success() {
        wx.showToast({
          title: "预约成功",
          icon: "success",
          duration: 2000,
        });

        that.setData({
          sheetShow: false,
          autoFocus: false,
        });
      },
    });
  },

  // 设置手机号
  setPhoneNumber() {
    const phoneNumber = this.data.phoneNumber;
    this.setData({
      phone: phoneNumber,
    });
  },

  //监听input获得焦点
  // inputFocus(e) {
  //   this.setData({ footerBlank: true });
  // },
  // inputBlur() {
  //   this.setData({ footerBlank: false });
  // },

  onCloseDialogPhone() {
    this.setData({
      dialogPhoneShow: false,
    });
  },

  // QR
  toQr: function (e) {
  //  const qr = e.currentTarget.dataset.qr;
    var qr=this.data.detail.qrImgList[0].url;
    wx.navigateTo({
      url: `/pages/card/index?qr=${qr}`,
    });
  },
});
